package com.card.manager.services.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.card.framework.mybatis.mapper.BatchCallBack;
import com.card.framework.mybatis.mapper.MyFrameworkSupperMapper;
import com.card.framework.mybatis.optimist.ModifiedByAnotherUserException;
import com.card.framework.page.model.PageModel;
import com.card.manager.dao.AbaMapper;
import com.card.manager.dao.AcaDayMapper;
import com.card.manager.dao.AcaMapper;
import com.card.manager.dao.AcaMonthMapper;
import com.card.manager.dao.AcaYearMapper;
import com.card.manager.dao.AcbMapper;
import com.card.manager.domain.Aba;
import com.card.manager.domain.Abb;
import com.card.manager.domain.Aca;
import com.card.manager.domain.AcaDayExample;
import com.card.manager.domain.AcaExample;
import com.card.manager.domain.AcaExample.Criteria;
import com.card.manager.domain.AcaMonthExample;
import com.card.manager.domain.AcaYearExample;
import com.card.manager.domain.Acb;
import com.card.manager.services.AcaService;
@Service("AcaServiceImpl")
public class AcaServiceImpl extends MyFrameworkSupperMapper implements AcaService {

	@Override
	public Map<String, Object> selectAcaForPage(Map<String,String> param, PageModel pageModel) {
		AcaMapper mapper = this.getMapper(AcaMapper.class);
		AcaExample acaExample = new AcaExample();
		//AcaExample.createCriteria().andUsernameIsNotNull();
		//AcaExample.createCriteria().andUsernameEqualTo(Aca.getUsername());
		if(pageModel.getRows() != 0)
			acaExample.setPage(pageModel);
		if(StringUtils.isNotEmpty(pageModel.getSort())) 
			acaExample.setOrderByClause(pageModel.getSort()+" "+pageModel.getOrder());
//		if(StringUtils.isNotEmpty(aca.getUsername())) 
//		acaExample.createCriteria().andUsernameEqualTo(aca.getUsername());
		Criteria criteria = acaExample.createCriteria();
		if(StringUtils.isNotBlank(param.get("idnumber"))){
			criteria.andAaaOwnerCardLike("%" + param.get("idnumber") + "%");
		}
		if(StringUtils.isNotBlank(param.get("abaid"))){
			criteria.andAbaidLike("%" + param.get("abaid") + "%");
		}
		if(StringUtils.isNotBlank(param.get("namesimp"))){
			criteria.andAabNamesimpLike("%" + param.get("namesimp") + "%");
		}
		if(StringUtils.isNotBlank(param.get("serialnumber"))){
			criteria.andSerialnumberLike("%" + param.get("serialnumber") + "%");
		}
		if(StringUtils.isNotBlank(param.get("dateFrom"))){
			try {
				criteria.andConsdateGreaterThanOrEqualTo(DateUtils.parseDate(param.get("dateFrom"), new String[]{"yyyy-MM-dd"}));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(StringUtils.isNotBlank(param.get("orderflg"))){
			criteria.andOrderflgEqualTo(Byte.parseByte(param.get("orderflg")));
		}
		if(StringUtils.isNotBlank(param.get("dateTo"))){
			try {
				criteria.andConsdateLessThanOrEqualTo(DateUtils.parseDate(param.get("dateTo"), new String[]{"yyyy-MM-dd"}));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		List<Aca> list =null;
		try{
		criteria.andDelflgEqualTo((byte)1);
		list = mapper.selectByExampleFetchJoin(acaExample);
		}catch(Exception e){
			e.printStackTrace();
		}
		Map<String, Object> modelMap = new HashMap<String, Object>();  
		System.out.println("pageModel.getTotalCount()="+pageModel.getTotalCount());
		System.out.println("pageModel.list()="+list.size());
	    modelMap.put("total", pageModel.getTotalCount());  
	    modelMap.put("rows", list); 
		
	    return modelMap;
	}

	@Override
	public void deleteAcas(final List<Aca> aca)
			throws ModifiedByAnotherUserException, Exception {
		batchSubmit(AcaMapper.class,new BatchCallBack() {
			@Override
			public <E> void batchCallBack(E mapper) {
				if(aca != null && aca.size() > 0) {
					for(Aca a :aca){
						a.setDelflg((byte)0);
						((AcaMapper) mapper).updateByPrimaryKeySelective(a);
					}
				}
			}
		});
	}
	@Override
	@Transactional
	public void addOrUpdate(Aca aca) {
		try{
			AcaMapper mapper = this.getMapper(AcaMapper.class);
			//Aaa queryResult = mapper.selectByPrimaryKey(aaa.getUserid());
			if(aca.getId()==null){
				mapper.insert(aca);
			}else
			{
				AcaExample acaExample = new AcaExample();
				acaExample.createCriteria().andIdEqualTo(aca.getId());
				mapper.updateByExample(aca, acaExample);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public Aca getById(String id) {
		AcaMapper mapper = this.getMapper(AcaMapper.class);
	    return mapper.selectByPrimaryKey(id);
	}
	@Override
	@Transactional
	public void returnAac(String acaid, String returnReason,
			BigDecimal returnMoney,String returnUserid) {
		AcaMapper acaMapper = this.getMapper(AcaMapper.class);
		AcbMapper acbMapper = this.getMapper(AcbMapper.class);
		AbaMapper abaMapper = this.getMapper(AbaMapper.class);
		Aca aca = acaMapper.selectByPrimaryKey(acaid);
		aca.setOrderflg((byte)2);
		acaMapper.updateByPrimaryKey(aca);
		
		Acb acb = new Acb();
		acb.setId(aca.getId());
		acb.setAacid(aca.getAacid());
		acb.setAbaid(aca.getAbaid());
		acb.setAabid(aca.getAabid());
		acb.setConsdate(aca.getConsdate());
		acb.setConsmoney(aca.getConsmoney());
		acb.setFee(aca.getFee());
		acb.setCreatuserid(aca.getCreatuserid());
		acb.setDelflg((byte)1);
		acb.setMoneytype(aca.getMoneytype());
		acb.setOrderflg((byte)2);
		acb.setReturnmoney(returnMoney);
		acb.setReturnreason(returnReason);
		acb.setReturntime(new Date());
		acb.setReturnuserid(returnUserid);
		acb.setSerialnumber(aca.getSerialnumber());
		acbMapper.insert(acb);
		
		Aba aba = abaMapper.selectByPrimaryKey(aca.getAbaid());
		if(aca.getMoneytype() == 1){//电字钱包
			aba.setEmoney(aba.getEmoney() + returnMoney.doubleValue());
		}else{//电字帐户
			aba.setMoney(aba.getMoney() + returnMoney.doubleValue());
		}
		abaMapper.updateByPrimaryKey(aba);
	}

	@Override
	public Map<String, Object> selectAcaSumForPage(Map<String, String> param,
			PageModel pageModel) {
		@SuppressWarnings("rawtypes")
		List list = null;
		List footer = null;
		if("3".equals(param.get("timeType"))){//day
			AcaYearMapper mapper = this.getMapper(AcaYearMapper.class);
			AcaYearExample example = new AcaYearExample();
			if(pageModel.getRows() != 0)
				example.setPage(pageModel);
			if(StringUtils.isNotEmpty(pageModel.getSort())) 
				example.setOrderByClause(pageModel.getSort()+" "+pageModel.getOrder());
			
			com.card.manager.domain.AcaYearExample.Criteria criteria = example.createCriteria();
			if(StringUtils.isNotBlank(param.get("aacid")))
				criteria.andAacidEqualTo(param.get("aacid"));
			if(StringUtils.isNotBlank(param.get("aabid")))
				criteria.andAabidEqualTo(Long.parseLong(param.get("aabid")));
			if(StringUtils.isNotBlank(param.get("timeFrom"))){
				String v = param.get("timeFrom").substring(0,4);
				criteria.andTimestrGreaterThanOrEqualTo(v);
			}
			if(StringUtils.isNotBlank(param.get("timeTo"))){
				String v = param.get("timeTo").substring(0,4);
				criteria.andTimestrLessThanOrEqualTo(v);
			}
			list = mapper.selectByExample(example);
			footer = mapper.sumByExample(example);
		}else if("2".equals(param.get("timeType"))){//month
			AcaMonthMapper mapper = this.getMapper(AcaMonthMapper.class);
			AcaMonthExample example = new AcaMonthExample();
			if(pageModel.getRows() != 0)
				example.setPage(pageModel);
			if(StringUtils.isNotEmpty(pageModel.getSort())) 
				example.setOrderByClause(pageModel.getSort()+" "+pageModel.getOrder());
			
			com.card.manager.domain.AcaMonthExample.Criteria criteria = example.createCriteria();
			if(StringUtils.isNotBlank(param.get("aacid")))
				criteria.andAacidEqualTo(param.get("aacid"));
			if(StringUtils.isNotBlank(param.get("aabid")))
				criteria.andAabidEqualTo(Long.parseLong(param.get("aabid")));
			if(StringUtils.isNotBlank(param.get("timeFrom"))){
				String v = param.get("timeFrom").substring(0,7).replaceAll("-", "");
				criteria.andTimestrGreaterThanOrEqualTo(v);
			}
			if(StringUtils.isNotBlank(param.get("timeTo"))){
				String v = param.get("timeTo").substring(0,7).replaceAll("-", "");
				criteria.andTimestrLessThanOrEqualTo(v);
			}
			list = mapper.selectByExample(example);
			footer = mapper.sumByExample(example);
		}else{//year
			AcaDayMapper mapper = this.getMapper(AcaDayMapper.class);
			AcaDayExample example = new AcaDayExample();
			if(pageModel.getRows() != 0)
				example.setPage(pageModel);
			if(StringUtils.isNotEmpty(pageModel.getSort())) 
				example.setOrderByClause(pageModel.getSort()+" "+pageModel.getOrder());
			
			com.card.manager.domain.AcaDayExample.Criteria criteria = example.createCriteria();
			if(StringUtils.isNotBlank(param.get("aacid")))
				criteria.andAacidEqualTo(param.get("aacid"));
			if(StringUtils.isNotBlank(param.get("aabid")))
				criteria.andAabidEqualTo(Long.parseLong(param.get("aabid")));
			if(StringUtils.isNotBlank(param.get("timeFrom"))){
				String v = param.get("timeFrom").replaceAll("-", "");
				criteria.andTimestrGreaterThanOrEqualTo(v);
			}
			if(StringUtils.isNotBlank(param.get("timeTo"))){
				String v = param.get("timeTo").replaceAll("-", "");
				criteria.andTimestrLessThanOrEqualTo(v);
			}
			list = mapper.selectByExample(example);
			footer = mapper.sumByExample(example);
		}
		Map<String, Object> modelMap = new HashMap<String, Object>();  
	    modelMap.put("total", pageModel.getTotalCount());  
	    modelMap.put("rows", list); 
	    modelMap.put("footer", footer); 
	    return modelMap;
	}
	public static void main(String[] args){
		String a = "2012-01-01";
		System.out.println(a.substring(0,4));
	}
}
